// 引入 request 文件
import request from '@/utils/base.js'
import { getRefreshUser } from '@/api/wallet.js'

// 微信id
export const wxid ='gh_85adb5b7352f' //微信id
export const clientId = '073820240321128890'  // 申请金康云登录成功后，分配给应用的appid 后续请求的appid都是这个
export const clientSecret = 'fa1c7b3f5494bf1c9d1a3e73433a66e6'  // 客户端密钥

export function getOpenId(data) {
	return request({
		method: 'GET',
		data,
		url: '/oauth/authorize',
		type: 3
	})
}

//获取小程序token
export function getwxtoken(data) {
	return request({
		method: 'POST',
		data,
		url: '/oauth/authorize/getWxAppletAccessToken',
		type: 3
	})
}

//获取小程序openId
export function getEndOpenId(data) {
	return request({
		method: 'POST',
		data,
		url: '/oauth/me',
		type: 3
	})
}

//获取用户信息
export function getUserInfo(data) {
	return request({
		method: 'POST',
		data,
		url: '/oauth/user/getUserInfo',
		type: 3
		// urlType:1
	})
}

// 绑定用户手机号
export function bindPhone(data) {
	return request({
		method: 'POST',
		data,
		url: '/oauth/Authorize/bindingWxAppletPhone',
		type: 3
	})
}


// 获取临时票据
export function getTicket(data) {
	return request({
		method: 'POST',
		data,
		url: '/oauth/Ticket/getUserApiTicket',
		type: 3
	})
}

// 授权登录
export function bindingWxApp(data) {
	return request({
		method: 'POST',
		data,
		url: '/oauth/Authorize/bindingWxAppletRegUser',
		type: 3
	})
}

// 登录
export function login() {
	uni.showLoading({
		title: '请稍后...'
	})
	return new Promise((resolve, rejcet)=>{
		uni.login({
			success:(res)=> {
				console.log('res', res)
				// return
				let param={
					"response_type":'code',
					"client_id": clientId,
					"state":Math.round(Math.random()*10),
					"scope":'get_wxapplet_user_info',
					"wxid":wxid,
					"redirect_uri":"http://ai.aimlt.com",
					"wx_code": res.code
				}
				getOpenId(param).then(req => {
					if(req.errcode && req.errcode!=200){
						uni.showToast({
							title:'未知错误('+req.errcode+')',
							icon:'none',
							duration:5000
						})
					} else {
						uni.getUserInfo({
							success:(userForm)=> {
								let tokenStr={
									"wxid": wxid,
									"client_id": clientId,
									"code": req.code
								}
								getwxtoken(tokenStr).then(tokenRes => {
									// console.log('tokenRes', tokenRes)
									if(tokenRes.errcode && tokenRes.errcode!=200){
										uni.showToast({
											title:'未知错误('+tokenRes.errcode+')',
											icon:'none',
											duration:5000
										})
									} else {
										console.log('tokenRes', tokenRes)
										uni.setStorageSync('acctoken', tokenRes.access_token)
										let openIdStr = {
											"access_token": tokenRes.access_token
										}
										if(tokenRes.is_binding_mobile == '0') {
											console.log('需要绑定手机号')
											uni.hideLoading()
											resolve(tokenRes)
										} else {
											getEndOpenId(openIdStr).then(openIdReq => {
												console.log('openIdReq', openIdReq)
												if(openIdReq.errcode && openIdReq.errcode!=200){
													uni.showToast({
														title:'未知错误('+openIdReq.errcode+')',
														icon:'none',
														duration:5000
													})
												} else {
													uni.setStorageSync('openid', openIdReq.openid)
													let useStr = {
														"access_token": tokenRes.access_token,
														"appid": clientId,
														"openid": openIdReq.openid
													}
													// 储存oauth_consumer_key
													getUserInfo(useStr).then(userInfo => {
														console.log('userInfo', userInfo)
														uni.setStorageSync('oauthConsumerKey', userInfo.oauth_consumer_key)
														uni.setStorageSync('portrait', userInfo.portrait)
														let ticketStr = {
															"oauth_consumer_key": userInfo.oauth_consumer_key,
															"appid": clientId,
															"openid": openIdReq.openid
														}
														getTicket(ticketStr).then(ticket => {
															console.log(ticket, 'ticket')
															uni.setStorageSync('apiticket', ticket.api_ticket );
															uni.navigateBack()
															getRefreshUser().then(info => {
																console.log(info, 'info')
															})
														})
														resolve(userInfo)
													}).catch(err => {
														console.log('1')
														uni.hideLoading()
													})
												}
											}).catch(err => {
												console.log('2')
												uni.hideLoading()
											})
										}
									}
								}).catch(err => {
									console.log('3')
									uni.hideLoading()
								})
							}
						})
					}
				}).catch(err=>{
					console.log('err',err)
					uni.hideLoading()
				})
			}
		})
	})
}


// 账号密码登录
export function loginByPassword(data) {
	return request({
		method: 'POST',
		data,
		url: '/oauth/Token/password',
		type: 3
	})
}


// 获取用户信息 全局
export function getUserMsg() {
	let useStr = {
		"access_token": uni.getStorageSync('acctoken'),
		"appid": clientId,
		"openid": uni.getStorageSync('openid')
	}
	getUserInfo(useStr).then(userInfo => {
		uni.setStorageSync('oauthConsumerKey', userInfo.oauth_consumer_key)
		uni.setStorageSync('portrait', userInfo.portrait)
	})
}

